package com.anxinr.proxy;

import com.anxinr.execute.ThreadPoolExecute;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author : anxinr
 * @date : 2022/10/13 11:33
 */
public class ThreadPoolExecutorInvocationHandler <T> implements MethodInterceptor {
    /**加入线程池*/
    private ThreadPoolExecute execute = ThreadPoolExecute.getInstance() ;
    private T target ;

    public void setTarget(T target){
        this.target = target ;
    }

    public Object getProxyInstance(){
        /**cglib工具类*/
        Enhancer en = new Enhancer();
        /**设置父类*/
        en.setSuperclass(target.getClass());
        /**设置回调函数*/
        en.setCallback(this);
        return en.create() ;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        AtomicReference<Object> obj = new AtomicReference<>() ;
        execute.execute(()->{
            try {
                obj.set(method.invoke(target, objects));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return obj.get();
    }
}
